package org.extframework.ld.encryption;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * @author : Dong.Li
 * @created : 2013-1-17
 * @version : 1.0
 * @description :
 */
public class JsScriptEngine {
	private static String jsEngineCode;
	   private static Invocable inv;
	 
	   static
	   {
	     InputStream inputStream = JsScriptEngine.class.getResourceAsStream("encryption.js");
	 
	     byte[] b = (byte[])null;
	     try {
	       int ava = inputStream.available();
	       b = new byte[ava];
	     } catch (IOException e) {
	       b = new byte[1024];
	     }
	     try
	     {
	       inputStream.read(b);
	     } catch (IOException e) {
	       e.printStackTrace();
	     }
	     try
	     {
	       jsEngineCode = new String(b, "GBK");
	     } catch (UnsupportedEncodingException e) {
	       e.printStackTrace();
	     }
	 
	     ScriptEngineManager factory = new ScriptEngineManager();
	     ScriptEngine engine = factory.getEngineByName("JavaScript");
	     try
	     {
	       engine.eval(jsEngineCode);
	       inv = (Invocable)engine;
	     } catch (ScriptException e) {
	       e.printStackTrace();
	     }
	   }
	 
	   public static void main(String[] args) throws ScriptException, NoSuchMethodException {
//	     String ss = engineCode("lidong - - �sfdasdfgasdfa==asdf-a0=sdgas-0d9g0-a9sd-0gasd-098gasdgfunction encryptionCode(e){var a=s.length;var c=++){a+=String.fromCharCode(b[c])}return a};");
	 
//	     System.out.println("���ܺ�:" + ss);
//	     String sss = unEngineCode(ss);
//	     System.out.println("���ܺ�:" + sss);
	   }
	 
	   public static final String engineCode(String str)
	     throws ScriptException, NoSuchMethodException
	   {
	     return inv.invokeFunction("encryptionCode", new Object[] { str }).toString();
	   }
	 
	   public static final String unEngineCode(String str)
	     throws ScriptException, NoSuchMethodException
	   {
	     return inv.invokeFunction("unEncryptionCode", new Object[] { str }).toString();
	   }

}
